package com.yand.thinkingInJava.thinkingInJava21.stopThread;


import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Count{
    private int count = 0;
    private Random rand = new Random(47);

    /**
     * 累加
     * @return
     */
    public synchronized int increment(){
        int temp = count;

        if(rand.nextBoolean()){
            Thread.yield();
        }

        return (count = ++temp);
    }

    //返回总数
    public synchronized int value(){
        return count;
    }
}


/**
 * 大门类
 */
class Entrance implements Runnable{

    private static Count count = new Count();

    private static List<Entrance> entrances =
               new ArrayList<>();
    private int number = 0;

    private int id ;

    private static volatile boolean cancaed = false;

    public static void cancel(){
        cancaed = true;
    }

    public Entrance(int id){
        this.id = id;
        entrances.add(this);
    }

    @Override
    public void run() {
        while(!cancaed){

                ++number;

            System.out.println(this + " Total: "+count.increment());
            try{
                TimeUnit.MILLISECONDS.sleep(100);
            }catch (InterruptedException e){
                System.out.println("Sleep interrupted");
            }




        }

        System.out.println("Stopping "+this);
    }

    public  int getValue(){
        return number;
    }

    public String toString(){
        return "Entrance "+id + ": "+getValue();
    }

    public static int getTotalCount(){
        return count.value();
    }

    public static int sumEntrances(){
        int sum = 0;
        for(Entrance entrance : entrances){
            sum += entrance.getValue();
        }

        return sum;
    }
}


/**
 * 停止线程的方法， 通过一个开关作为标识，进行关闭线程的办法 while中关闭后，不循环直接退出
 */
public class OrnamentalGarden {

    public  static void main(String [] args) throws InterruptedException {
       ExecutorService exec =  Executors.newCachedThreadPool();
       for(int i = 0 ; i < 5 ; i ++){
           exec.execute(new Entrance(i));
       }

       TimeUnit.SECONDS.sleep(3);

       Entrance.cancel();
       exec.shutdown();
       if(!exec.awaitTermination(250,TimeUnit.MILLISECONDS)){
           System.out.println("Some tasks were not terminated!");
       }
       System.out.println("Total: "+Entrance.getTotalCount());
       System.out.println("Sum of Entrances: "+Entrance.sumEntrances());





    }


}
